package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 使用多线程实现多用户鹦鹉学舌
 * @author admin
 *
 */
public class Chat implements Runnable {
	private Socket socket = null;

	public Chat(Socket client) {
		super();
		this.socket = client;
	}

	@Override
	public void run() {
		InputStream inputStream = null;
		OutputStream outputStream = null;

		try {
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			boolean chatting = true;
			// 设置缓存，发送的数据长度不能大于512字节
			byte[] b = new byte[512];
			while (chatting) {
				// 等待并接收客户端发送的数据-有阻塞作用
				int len = inputStream.read(b);
				String string = new String(b, 0, len).trim();
				System.out.println(string);
				// 发送原话回客户端
				outputStream.write(("parrot: " + string).getBytes());
				if ("quit".equalsIgnoreCase(string)) {
					chatting = false;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if (socket != null) {
						try {
							socket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
